<template>
    <el-menu
    :default-active="activeIndex"
    class="el-menu-demo"
    mode="horizontal"
    @select="handleSelect"
    style="display: flex; justify-content: center;"
  >
  <el-menu-item @click="getSpuList()">全部</el-menu-item>
    <el-menu-item :index="item.id" v-for="item in categoryList" :key="item.id">{{ item.name }}</el-menu-item>
    
  </el-menu>

    <el-table :data="filterTableData" style="width: 100%">
        <el-table-column label="商品图片" prop="skuPicture">
            <template v-slot:default="{ row }">
                <img :src="row.picture" style="width: 130px; " />
            </template>
        </el-table-column>
        <el-table-column label="商品名" prop="name" />
        <el-table-column label="价格" prop="price" />
        <el-table-column label="库存" prop="stock" />
        <el-table-column align="right">
            <template #header>
                <el-input v-model="search" size="small" placeholder="Type to search" />
            </template>
            <template #default="scope">
                <el-button size="small" @click="handleEdit(scope.$index, scope.row)">修改</el-button>


                <el-popconfirm confirm-button-text="Yes" cancel-button-text="No" :icon="InfoFilled" icon-color="#626AEF"
                    title="确定要删除吗" @confirm="handleDelete(scope.$index, scope.row)" @cancel="cancelEvent">
                    <template #reference>
                        <el-button size="small" type="danger">删除</el-button>
                    </template>
                </el-popconfirm>

            </template>
        </el-table-column>
    </el-table>

    <el-dialog v-model="dialogTableVisible" title="sku" width="80%">
        <el-table :data="skuList">
            <el-table-column property="id" label="ID"  />
            <el-table-column label="商品图片">
                    <template #default="{ row, $index }">
                        <el-upload class="avatar-uploader" action="" :http-request="uploadSkuPicture"
                            :data="{ rowIndex: $index }" :show-file-list="false" :before-upload="beforeAvatarUpload">
                            <img v-if="row.picture" :src="row.picture" class="avatar" />
                            <el-icon v-else class="avatar-uploader-icon">
                                <Plus />
                            </el-icon>
                        </el-upload>
                    </template>
                </el-table-column>
            <el-table-column property="name" label="sku"  />
            <el-table-column label="销售价（元）">
                    <template #default="{ row }">
                        <el-input-number v-model="row.price" :precision="2" :step="0.1" :max="10000" />
                    </template>
                </el-table-column>
                <el-table-column label="市场价（元）">
                    <template #default="{ row }">
                        <el-input-number v-model="row.marketPrice" :precision="2" :step="0.1" :max="10000" />
                    </template>
                </el-table-column>
                <el-table-column label="成本价（元）">
                    <template #default="{ row }">
                        <el-input-number v-model="row.costPrice" :precision="2" :step="0.1" :max="10000" />
                    </template>
                </el-table-column>
                <el-table-column label="库存">
                    <template #default="{ row }">
                        <el-input-number v-model="row.stock" :precision="0" :step="1" :max="100000" />
                    </template>
                </el-table-column>
                <el-table-column label="状态">
                    <template #default="{ row }">
                        <el-select v-model="row.status" class="m-2" placeholder="Select">
                            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label"
                                :value="item.value" />
                        </el-select>
                    </template>
                </el-table-column>
            <el-table-column align="right">

            <template #default="scope">

                <el-button size="small" @click="handleSkuEdit(scope.$index, scope.row)">修改</el-button>
                
            </template>
        </el-table-column>
        </el-table>
    </el-dialog>
</template>
  
<script lang="ts" setup>
import { computed, onMounted, reactive, ref } from 'vue'
import api from '@/api'
import { ElNotification, UploadProps } from 'element-plus';
import { useRouter } from 'vue-router';
import { InfoFilled } from '@element-plus/icons-vue'


const router = useRouter()



const search = ref('')
const filterTableData = computed(() =>
    spuList.value.filter(
        (data) =>
            !search.value ||
            data.name.toLowerCase().includes(search.value.toLowerCase())
    )
)
const handleEdit = (index: number, row: any) => {
    dialogTableVisible.value = true
    getSkuBySpuId(row.id)
}

function getSkuBySpuId(id:string){
    api.shop.getAllSkuBySpuId(id)
        .then(response => {
            // 在这里可以处理提交成功后的逻辑

            skuList.value = response.data.data
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

const handleSkuEdit  = (index: number, row: any) => {
    row.createTime = null
    row.updateTime = null
    api.shop.editSku(row)
    .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getSkuBySpuId(row.spuId)
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })


        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}

const handleDelete = (index: number, row: any) => {
    api.shop.deleteSpuById({ id: row.id })
        .then(response => {
            // 在这里可以处理提交成功后的逻辑
            getSpuList()
            ElNotification({
                title: 'Success',
                message: response.data.msg,
                type: 'success',
                duration: 1500
            })


        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
            // 在这里可以处理提交失败后的逻辑
        });
}


const spuList = ref([
    {
        id: '',
        name: '',
        picture: ''
    }
])

onMounted(() => {
    getSpuList()
    getCategoryList()
})

const qurey = ref({
    categoryId: '',
    keyWord: ''
})

function getSpuList() {
    api.shop.getSpuList({ categoryId: qurey.value.categoryId, keyWord: qurey.value.keyWord })
        .then(response => {
            spuList.value = response.data.data
        })
        .catch(error => {
            ElNotification({
                title: 'Error',
                message: error.data.msg,
                type: 'error',
                duration: 1500
            })
        });

}

const confirmEvent = () => {
    console.log('confirm!')
}
const cancelEvent = () => {
    console.log('cancel!')
}

const dialogTableVisible = ref(false)

const skuList = ref([
    {
        picture: ''
    }
])

const statusOptions = [
    {
        value: 1,
        label: '启用',
    },
    {
        value: 0,
        label: '禁用',
    },
]


const beforeAvatarUpload: UploadProps['beforeUpload'] = (rawFile) => {

return true
}



const uploadSkuPicture: UploadProps['httpRequest'] = (uploadFile) => {
const index = Number(uploadFile.data.rowIndex);
const file = uploadFile.file
// 创建FormData对象
const formData = new FormData();
// 将上传的文件添加到FormData中
formData.append('file', file);
return api.shop.uploadSkuPicture(formData)
    .then(response => {
        // 在这里可以处理提交成功后的逻辑
        // 根据索引值找到对应的行数据
        const row = skuList.value[index];

        // 更新行数据的属性
        row.picture = response.data.data; // 以picture属性为例
        ElNotification({
            title: 'Success',
            message: response.data.msg,
            type: 'success',
            duration: 1500
        });

    })
    .catch(error => {
        ElNotification({
            title: 'Error',
            message: error.data.msg,
            type: 'error',
            duration: 1500
        });
    });
}

const activeIndex = ref('1')
const handleSelect = (key: string) => {
  api.shop.getSpuList({ categoryId: key, keyWord: qurey.value.keyWord })
    .then(response => {
      spuList.value = response.data.data
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    });
}

const categoryList = ref([
  {
    id:'',
    name: ''
  }
])

function getCategoryList(){
  api.shop.getCategoryList()
  .then(response => {
    categoryList.value = response.data.data
    })
    .catch(error => {
      ElNotification({
        title: 'Error',
        message: error.data.msg,
        type: 'error',
        duration: 1500
      })
    });
}
</script>
<style scoped>
.el-button--text {
    margin-right: 15px;
}

.el-select {
    width: 300px;
}

.el-input {
    width: 300px;
}

.dialog-footer button:first-child {
    margin-right: 10px;
}

.avatar-uploader .avatar {
    width: 80px;
    height: 80px;
    display: block;
}

.avatar-uploader .el-upload {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 80px;
    height: 80px;
    text-align: center;
}




.avatar-uploader1 .avatar1 {
    width: 178px;
    height: 178px;
    display: block;
}

.avatar-uploader1 .el-upload1 {
    border: 1px dashed var(--el-border-color);
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
    transition: var(--el-transition-duration-fast);
}

.avatar-uploader .el-upload:hover {
    border-color: var(--el-color-primary);
}

.el-icon.avatar-uploader-icon1 {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    text-align: center;
}
</style>